<template>
  <div>
    <el-drawer
      v-model="dialogVisible"
      :title="dialogStatus==='create'?'新增配置': '编辑配置'"
      width="600px"
      @close="reset"
    >
      <div class="scene-dialog">
        <el-form 
          ref="formRef"
          :model="formItem" 
          :rules="rules"
          label-width="100"
          label-position="top"
          :disabled="!isDisabled"
        >
          <el-form-item label="配置名称" prop="configName">
            <el-input v-model="formItem.configName" />
          </el-form-item>

          <el-form-item label="所属设备类型" prop="equipType">
            <el-select 
                v-model="formItem.equipType" 
                clearable
                placeholder="请选择"
                @change="getEquipList"
              >
                <el-option 
                  v-for="item in equipOption"
                  :label="item.name" 
                  :value="+item.value" 
                />
            </el-select>
          </el-form-item>

          <el-form-item label="上传配置文件" prop="configUrl">
            <el-button type="primary" 
              link 
              @click="handleDownload" 
              style="position: absolute;right: 0;top: -30px;"
            >
              点击下载配置模板
            </el-button>
            <el-upload
              ref="upload"
              :file-list="formItem.uploadList"
              accept=".xls,xlsx,.XLS,.XLSX" 
              :show-file-list="true"
              :action="`/base-api/file/upload`" 
              :limit="1"
              :headers="headers" 
              :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile)"
              :on-error="handleUploadError"
              :on-remove="removeItem"
              :on-exceed="handleExceed"
              name="files"
              style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
              auto-upload
            >
              <el-button>
                点击上传
              </el-button>
            </el-upload>
          </el-form-item>

          <el-form-item label="配置描述" prop="configDes">
            <el-input v-model="formItem.configDes" />
          </el-form-item>

          <el-form-item label="项目" prop="projectIds">
            <el-select 
              v-model="formItem.projectIds" 
              multiple
              collapse-tags
              collapse-tags-tooltip
              clearable
              placeholder="请选择"
              @change="handleProjectChange"
            >
              <el-option 
                v-for="item in projectOption"
                :label="item.projectName" 
                :value="+item.id" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择设备" prop="ids">
            <el-table 
              ref="tableRef"
              :data="tableData.list" 
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="40" />
              <el-table-column prop="equipName" label="设备名称" />
              <el-table-column prop="macCode" label="设备MAC" />
              <el-table-column prop="pkgVersion" label="当前版本号" width="100" />
            </el-table>
          </el-form-item>

        </el-form>
      </div>
        
      <template #footer>
        <div class="table-footer">
          共{{tableData.total}}个设备，已选择 <span>{{multipleSelection?.length}}</span> 个设备
        </div>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus==='create'?createData():updateData()"
          >提交</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, genFileId } from 'element-plus'
import { getToken } from '@/utils/user'
import { editRemote, getDist, getProjectList, addRemote, getUpgradeEquipList } from '@/api/collect'
import { validate } from '@/utils/validate'

const isDisabled = ref(true)

const formRef = ref<any>(null)

const formItem = reactive({
  uploadList: [],
  configName: '',
  equipType: '',
  configUrl: '',
  configDes: '',
  originName: '',
  projectIds: [],
  ids: [],
})

const rules = reactive({
  configName: [{ required: true, message: '请输入', trigger: 'blur' }],
  equipType: [{ required: true, message: '请选择', trigger: 'change' }],
  projectIds: [{ required: true, message: '请选择', trigger: 'change' }],
  configUrl: [{ required: true, message: '请上传', trigger: 'blur' }],
  ids: [{ required: true, message: '请选择设备', trigger: 'blur' }],
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

const equipOption = ref<any>([])

const getEquipTypeList = () => {
  getDist('DC00011').then((res: any)=>{
    equipOption.value = res.data
  })
  .catch((err: any) => {
    console.error('err', err.msg)
  })
}

getEquipTypeList()

// 文件上传
// 是否只读
// const readonly = computed(() => props.state == 'check')

const handleUploadSuccess = (data: any, uploadFile: any,) => {
  if (data.success == true) {
    // console.log('data', data)
    // TODO 回显用，后端字段修改 uploadUrl=>url, photoName=>name
    const params = {
      name: '',
      url: '',
    }
    // TODO 回显用，后端字段修改 uploadUrl=>url, photoName=>name
    params.url = data.data[0]
    params.name = uploadFile.name
    formItem.originName = uploadFile.name
    formItem.uploadList.push(params)
    // console.log('formItem.uploadPhotoDtoList', formItem.uploadPhotoDtoList)
    ElMessage.success(data.msg)
  } else {
    ElMessage.error(data.msg);
  }
}

const removeItem = (i: any) => {
  // console.log('remove-item', i)
  const removeIndex = formItem.uploadList.findIndex((item: any) => i.uploadUrl == item.uploadUrl)
  formItem.uploadList.splice(removeIndex, 1)
  // console.log('formItem.uploadPhotoDtoList', formItem.uploadPhotoDtoList)
}

const handleUploadError = (err: any) => {
  const message = JSON.parse(err.toString().replace('UploadAjaxError: ', '')).msg
  ElMessage.error(message)
}

const upload = ref()

const handleExceed = (files: any) => {
  upload.value!.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()
}

const token = getToken();

const headers = { Authorization: `${token}` }

const projectOption = ref<any>([])  

const handleProjectList = () => {
  getProjectList().then((res: any)=>{
    projectOption.value = res.data
  })
  .catch((err: any) => {
    console.error('err', err.msg)
  })
}

handleProjectList()

const handleDownload = () => {
  window.open('https://applet.shengweiswcr.com:32009/innovate/admin/ea82c99a-1828-4d47-a167-8de488c64897.xlsx')
}

const handleProjectChange = () => {
  getEquipList()
}

const tableData = reactive({
  list: [] as any,
  total: 0
})

const getEquipList = () => {
  if (formItem.projectIds.length == 0) return
  const params = {
    projectIds: formItem.projectIds,
    equipType: formItem.equipType
  }
  getUpgradeEquipList(params).then((res: any)=>{
    tableData.list = res.data
    tableData.total = res.data.length
  })
  .catch((err: any) => {
    console.error('err', err.msg)
  })
}

const multipleSelection = ref<any>([])

const tableRef = ref(null)

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val.map(item=>item.id);
  formItem.ids = multipleSelection.value
}


// 重置
const reset = () => {
  if (!formRef) return
  formRef.value.resetFields()
  formItem.uploadList = []
  tableData.list = []
  isDisabled.value = false
}

const emit = defineEmits(['listChange'])

const createData = async () => {
  formItem.configUrl = formItem.uploadList[0]?.url
  const valid = await validate(formRef)
  if (valid) {
    addRemote(formItem)
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('创建成功！')
    })
    .catch((err:any) => {
      dialogVisible.value = false
      ElMessage.error('创建失败！'+ err.msg)
    })
  }
}

const updateData = async () => {
  const valid = await validate(formRef)
  if (valid) {
    editRemote(formItem)
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('更新成功！')
    })
    .catch((err:any) => {
      dialogVisible.value = false
      ElMessage.error('更新失败！'+ err.msg)
    })
  }
}

defineExpose({ dialogVisible, formItem, isDisabled, dialogStatus, getEquipList, reset, tableRef, tableData, multipleSelection })
</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 20px;
}
// :deep(.el-drawer__header) {
//     padding: 32px 28px 10px 36px;
//     text-align: center;
// }
.table-footer {
  padding: 10px 0 20px;
  text-align: center;
  span {
    color: #03CCA1;
  }
}
.dialog-footer {
  padding: 10px 0;
  text-align: center;
}
</style>
